package com.example.controller;
import cn.hutool.core.util.StrUtil;
import com.example.dto.*;
import com.example.entity.SysStoreEntity;
import com.example.entity.SysTenantEntity;
import com.example.entity.SysUserEntity;
import com.example.exception.BaseException;
import com.example.model.api.Result;
import com.example.model.page.PageData;
import com.example.security.InfoDetail;
import com.example.security.SecurityUser;
import com.example.service.*;
import com.example.utils.ConvertUtils;
import com.example.utils.JSON;
import com.example.validator.AssertUtils;
import com.example.validator.ValidatorUtils;
import com.example.validator.group.AddGroup;
import com.example.validator.group.DefaultGroup;
import com.example.validator.group.UpdateGroup;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.web.bind.annotation.*;

import java.security.Security;
import java.util.List;

@Tag(name = "用户管理")
@RestController
@RequestMapping("user")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private Oauth2RegisteredClientService oauth2RegisteredClientService;

    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysStoreService sysStoreService;
    @Autowired
    private SysTenantService sysTenantService;

    @PostMapping("page")
    @Operation(summary = "分页")
    @PreAuthorize("hasAuthority('sys:user:page')")
//    @PreAuthorize("hasAuthority('message.read')")
    public Result<PageData<SysUserDTO>> page(@RequestBody SysQueryUserDTO sysQueryUserDTO){
        PageData<SysUserDTO> page = sysUserService.selectPage(sysQueryUserDTO);
        return new Result<PageData<SysUserDTO>>().ok(page);
    }

    @GetMapping("info")
    @Operation(summary = "登录用户信息")
    public Result<SysUserDTO> info(){
        SysUserEntity sysUserEntity = sysUserService.selectById(SecurityUser.getUserId());
        SysUserDTO data = ConvertUtils.sourceToTarget(sysUserEntity, SysUserDTO.class);

        InfoDetail user = SecurityUser.getUser();
        data.setIsHeadStore(user.getIsHeadStore());
        data.setIsSuperTenant(user.getIsSuperTenant());
        data.setTentantId(user.getTenantId());
        data.setStoreId(user.getStoreId());

        SysStoreEntity sysStoreEntity = sysStoreService.selectById(user.getStoreId());
        String storeName = sysStoreEntity.getStoreName();
        data.setStoreName(storeName);

        SysTenantEntity sysTenantEntity = sysTenantService.selectById(user.getTenantId());

        String tentantName = StrUtil.isEmpty(sysTenantEntity.getName()) ? "周姨" : sysTenantEntity.getName();
        data.setTenantName(tentantName);

        return new Result<SysUserDTO>().ok(data);
    }

    @PutMapping("password")
    @Operation(summary = "修改密码")
    public Result<String> updatePassword(@RequestBody PasswordDTO passwordDTO){
        Long userId = SecurityUser.getUserId();
        passwordDTO.setId(userId);
        ValidatorUtils.validateEntity(passwordDTO);
        sysUserService.updatePassword(passwordDTO);
        return Result.success();
    }

    @PostMapping
    @Operation(summary = "保存")
//    @PreAuthorize("hasAuthority('sys:user:save')")
    public Result<String> save(@RequestBody SysUserDTO dto){
        InfoDetail user = SecurityUser.getUser();
        if (user == null) {
            throw new BaseException("用户未登录");
        }

//        dto.setTenantId(SecurityUser.getTenantId());
//        dto.setStoreId(SecurityUser.getStoreId());
//        Long clientPrimaryId = SecurityUser.getUser().getClientPrimaryId();
//        Oauth2RegisteredClientDTO oauth2RegisteredClientDTO = oauth2RegisteredClientService.get(String.valueOf(clientPrimaryId));
//        String clientSecretPlaintext = oauth2RegisteredClientDTO.getClientSecretPlaintext();
//        dto.setClientPrimaryId(clientPrimaryId);
//        dto.setClientSecretNoop(clientSecretPlaintext);

        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        sysUserService.save(dto);


        return Result.success();
    }

    @DeleteMapping
    @Operation(summary = "删除")
//    @LogOperation("Delete User")
//    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result<String> delete(@RequestBody List<Long> ids){
        AssertUtils.isListEmpty(ids, "数组参数不能为空");
        sysUserService.deleteIds(ids);
        return Result.<String>success();
    }



    @PutMapping
    @Operation(summary = "修改")
//    @PreAuthorize("hasAuthority('sys:user:update')")
    public Result<String> updateUserInfo(@RequestBody SysUserDTO dto){
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        sysUserService.update(dto);
        return Result.<String>success();
    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
//    @PreAuthorize("hasAuthority('sys:user:info')")
    public Result<SysUserDTO> get(@PathVariable("id") Long id){
        SysUserDTO sysUserDTO = sysUserService.getId(id);
        sysUserDTO.setDeptName(null);
        List<Long> userRoleIds = sysUserService.getUserRoleIds(id);
        sysUserDTO.setRoleIdList(userRoleIds);

        return new Result<SysUserDTO>().ok(sysUserDTO);
    }

    @Operation(summary = "查看登录用户权限")
    @GetMapping
    public Result<Authentication> authentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println(authentication.getAuthorities());
//        if(authentication.getPrincipal() == "anonymousUser") {
//            InfoDetail infoDetail = new InfoDetail();
//            infoDetail.setUsername("anonymousUser");
//            return new Result<InfoDetail>().ok(infoDetail);
//        }
//        JwtAuthenticationToken token = (JwtAuthenticationToken) authentication;
//        Object o = token.getTokenAttributes().get("infoDetail");
//        InfoDetail convert = JSON.convert(o, InfoDetail.class);
        return new Result<Authentication>().ok(authentication);
    }



}